package com.ks.winterwarmimage;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.esptouch.EspTouchManage;
import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.mqtt.MsgMqttService;
import com.ks.winterwarmimage.utils.BasicsUtil;
import com.ks.winterwarmimage.utils.CmdDataPacket;
import com.ks.winterwarmimage.utils.Constants;

public class UpdateDeviceNameActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG ="UpdateGroupNameActivity" ;
    private static final String base_topic="WinterWarmImage/dev/";
    private TextView textTitle,textDevId,textOldDevName,textDevCount,textUpdateState;
    private EditText textDevName;
    private String deviceId=null;
    private String newDevName = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_device_name);
        textTitle = findViewById(R.id.text_title);
        textTitle.setText(R.string.update_dev_name);
        textDevId = findViewById(R.id.text_dev_id);
        textOldDevName = findViewById(R.id.text_old_dev_name);
        textDevName = findViewById(R.id.text_dev_name);
        textDevCount = findViewById(R.id.text_dev_count);
        textUpdateState=findViewById(R.id.text_update_state);
        Bundle bundle=this.getIntent().getExtras();
        if(bundle!=null){
            if(bundle.containsKey(Constants.KEY_MAC_ID)) {
                deviceId = this.getIntent().getStringExtra(Constants.KEY_MAC_ID);
                textDevId.setText(deviceId.toUpperCase());
            }
            if(bundle.containsKey(Constants.KEY_DEV_NAME)) {
                textOldDevName.setText(this.getIntent().getStringExtra(Constants.KEY_DEV_NAME));
            }
        }
        textDevName.addTextChangedListener(groupChangedListener);
        findViewById(R.id.img_return).setOnClickListener(this);
        if(deviceId!=null) {
            findViewById(R.id.btn_update).setOnClickListener(this);
            bindMqttService();
        }
    }
    @Override
    protected void onDestroy() {
        if(deviceId!=null) {
            unMqttBroadcastReceiver();
        }
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.e(TAG,"按下Back或Home键退出");
            finishResult();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.img_return){
            finishResult();
        }else if (view.getId()==R.id.btn_update){
            if(deviceId!=null){
                String newDevName=textDevName.getText().toString();
                if(newDevName.length()==0) {
                    textUpdateState.setText(R.string.update_len_null);
                }else if(newDevName.getBytes(EspTouchManage.GB2312).length>25) {
                    textUpdateState.setText(R.string.update_len_exceed);
                }else{
                    textUpdateState.setText(R.string.update_start);
                    byte[] send_bytes=newDevName.getBytes(EspTouchManage.GB2312);
                    CmdDataPacket dataPacket=new CmdDataPacket(CmdDataPacket.CMD_UPDATE_DEV_NAME,send_bytes);
                    String id=BasicsUtil.removeMacColon(deviceId).toUpperCase();    //去除冒号
                    String topic="WinterWarmImage/phone/"+id;
                    MsgMqttService.publish(topic,dataPacket.toBytes(),0,false);
                }
            }
        }
    }
    @Override
    protected void onMessageArrived(MqttMag message) {
        super.onMessageArrived(message);
        String topic = message.getTopic().replace(base_topic, "");  //去掉基主题部分
        String id= BasicsUtil.removeMacColon(deviceId);    //去除冒号
        if(id.equalsIgnoreCase(topic)) {    //收到的消息和群组号一致
            receiveAnalysis(message.getMessage(), deviceId);
        }
    }
    /**完成返回*/
    private void finishResult(){
        if(newDevName!=null){
            Intent intent=new Intent();
            intent.putExtra(Constants.KEY_MAC_ID,deviceId);
            intent.putExtra(Constants.KEY_DEV_NAME,newDevName);
            setResult(RESULT_CODE+2,intent);
        }
        finish();
    }
    /***********************组文本输入框内容改变侦听器****************************/
    private TextWatcher groupChangedListener=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // 文本改变时的回调
            if(TextUtils.isEmpty(s)){
                textDevCount.setText("0/25");
            }else {
                int groupCount= s.toString().getBytes(EspTouchManage.GB2312).length ;
                textDevCount.setText(String.format("%d/25", groupCount));
                if(groupCount==0){
                    textDevCount.setTextColor(getColor(android.R.color.darker_gray));
                }else if(groupCount>0 && groupCount<=25){
                    textDevCount.setTextColor(getColor(android.R.color.holo_green_light));
                    textDevName.setTextColor(getColor(android.R.color.black));
                }else{
                    textDevCount.setTextColor(getColor(android.R.color.holo_red_light));
                    textDevName.setTextColor(getColor(android.R.color.holo_red_light));
                }
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    /**
     * 解析接收到的数据
     * @param data 接收到的数据
     * @param mac_id 设备号
     */
    private void receiveAnalysis(byte[] data,String mac_id) {
        if(mac_id!=null){
            CmdDataPacket cmdDataPacket = CmdDataPacket.fromBytes(data);  //将消息转为标准命令结构
            if(cmdDataPacket!=null && cmdDataPacket.command==CmdDataPacket.CMD_UPDATE_DEV_NAME_ACK){
                StringBuffer sb = new StringBuffer(textUpdateState.getText());
                sb.append("\n");
                if(cmdDataPacket.data[0]==CmdDataPacket.ESP_OK){
                    //更新成功
                    sb.append(getString(R.string.update_ok));
                    updateDeviceName(deviceId,textDevName.getText().toString());
                }else{
                    //更新失败
                    sb.append(getString(R.string.update_fail));
                }
                textUpdateState.setText(sb);
            }
        }
    }

    /**
     * 更新设备名称
     * @param mac_id 设备号
     * @param devName 设备名称
     */
    private void updateDeviceName(String mac_id,String devName){
        ContentValues values=new ContentValues();
        values.put(Constants.KEY_DEV_NAME,devName);
        int count=DatabaseManager.database.update(Constants.TABLE_DEV,values,Constants.KEY_MAC_ID+"=?",new String[]{mac_id});
        StringBuffer sb = new StringBuffer(textUpdateState.getText());
        sb.append("\n");
        if(count>0){
            sb.append(getString(R.string.update_local_ok));
        }else{
            sb.append(getString(R.string.update_local_fail));
        }
        textUpdateState.setText(sb);
        newDevName=devName;
    }
}